package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.config.Constant;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.CodeUtil;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.dao.LaundryFactoryVoDao;
import com.jsb.laundry.dao.OrdersFulfillmentDao;
import com.jsb.laundry.dao.OrdersFulfillmentItemDao;
import com.jsb.laundry.model.dto.HistoricalOrdersDetailsRequest;
import com.jsb.laundry.model.dto.OderPuRequest;
import com.jsb.laundry.model.dto.SystemRequest;
import com.jsb.laundry.model.dto.ViewOrderDetailsVoRequest;
import com.jsb.laundry.model.entity.*;
import com.jsb.laundry.model.vo.HistoricalOrdersDetailsListVo;
import com.jsb.laundry.service.OrderInfoService;
import com.jsb.laundry.service.OrderSplittingServiceImpl;
import com.jsb.laundry.service.impl.JsbOrderStatusLogServiceImpl;
import com.jsb.laundry.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api(tags = {"确认"})
@RestController
@RequestMapping("/system/")
public class OrderPaySplittingController {
    @Resource
    private OrderSplittingServiceImpl orderSplittingService;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private OrdersFulfillmentDao ordersFulfillmentDao;
    @Resource
    private JsbOrderStatusLogServiceImpl jsbOrderStatusLogService;
    @Resource
    private OrdersFulfillmentItemDao ordersFulfillmentItemDao;
    @Resource
    private LaundryFactoryVoDao laundryFactoryVoDao;
    @PostMapping("invitationRewardsSettl")
    public void invitationRewardsSettl(@RequestBody JSONObject data) {
        String userId = data.getString("userId");
        String userType = data.getString("userType");
        String inviteeUserId = data.getString("inviteeUserId");
        int amount = data.getInteger("amount");
        orderSplittingService.invitationRewardsSettl(userId,userType,inviteeUserId,amount);
    }
    @PostMapping("orderPaySplitting")
    public void OrderPaySplitting(@RequestBody SystemRequest systemRequest) {
        orderSplittingService.OrderPaySplitting(systemRequest.getOrderId(), systemRequest.getMoney());
    }
    @PostMapping("orderUserRecharge")
    public void OrderUserRecharge(@RequestBody SystemRequest systemRequest) {
        orderSplittingService.OrderUserRecharge(systemRequest.getOrderId(), systemRequest.getMoney());
    }
    @PostMapping("siteCommission")
    public void siteCommission(@RequestBody JSONObject object) {
        String shopsId = object.getString("shopsId");
        String orderId = object.getString("orderId");
        String[] split = orderId.split("-");
        String s = split[0];
        String substring = s.substring(2);
        int amount = object.getInteger("amount");

        orderSplittingService.siteCommission(shopsId,substring,amount,orderId);
    }

    @ApiOperation(value = "骑手取货", notes = "骑手取货", httpMethod = "POST")
    @PostMapping("pickUp")
    public WebResponse pickUp(@RequestBody OderPuRequest oderPuRequest) {
        String byOrderInfoByInMy = orderInfoService.findByOrderInfoTc(oderPuRequest.getOrderId(), oderPuRequest.getUserId());
//        if ("1".equals(byOrderInfoByInMy)) {
        String courierStatus = "2";
        orderInfoService.pickUp(courierStatus, oderPuRequest.getOrderId());
        orderInfoService.updfactoryStatus(oderPuRequest.getOrderId());
        orderInfoService.updorderStatus("9",oderPuRequest.getOrderId());

        //骑手待结算
        //查询改订单的金额
        int byPaidPrice = orderInfoService.findByPaidPrice(oderPuRequest.getOrderId());
        double money = byPaidPrice * Constant.rider_commission_percentage;
        //查询抢单用户id
        String riderInfoId = orderInfoService.findByRiderInfoId1(oderPuRequest.getOrderId());
        orderSplittingService.riderSplitting(oderPuRequest.getOrderId(),riderInfoId, (int) money);
        int direction = orderInfoService.findByOrderDirection(oderPuRequest.getOrderId());
        String byOrderStatus = orderInfoService.findByOrderStatus(oderPuRequest.getOrderId());

        jsbOrderStatusLogService.addLog(oderPuRequest.getOrderId(), byOrderStatus, String.valueOf(direction));
        return WebResponse.successData("1");
//        }
//        return WebResponse.success(ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getCode(), ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getMsg());

    }

    @ApiOperation(value = "确认送达", notes = "确认送达", httpMethod = "POST")
    @PostMapping("okUp")
    public WebResponse okUp(@RequestBody OderPuRequest oderPuRequest) {
//        String byOrderInfoByInMy = orderInfoService.findByOrderInfoTc(oderPuRequest.getOrderId(), oderPuRequest.getUserId());
//        if ("1".equals(byOrderInfoByInMy)) {
        String orderStatus = "3";
        orderInfoService.pickUp(orderStatus, oderPuRequest.getOrderId());
        int direction = orderInfoService.findByOrderDirection(oderPuRequest.getOrderId());
        String byOrderStatus = orderInfoService.findByOrderStatus(oderPuRequest.getOrderId());
        jsbOrderStatusLogService.addLog(oderPuRequest.getOrderId(), byOrderStatus, String.valueOf(direction));
//        orderEnterFactory(oderPuRequest.getOrderId());
        JSONObject object =new JSONObject();
        object.put("orderId",oderPuRequest.getOrderId());
        HttpUtil.sendPost("http://127.0.0.1:30000/admin/laundryShops/orderEnterShops",null, JSONObject.toJSONString(object));
        return WebResponse.successData("1");
//        }
//        return WebResponse.success(ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getCode(), ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getMsg());

    }
    /**
     * 订单入工厂表 jsb_orders_factory、jsb_orders_factory_item
     */
    private void orderEnterFactory(String payId) {
        JsbOrdersFactory jsbOrdersFactory = laundryFactoryVoDao.getOrdersFactoryInfo(payId);
        if (jsbOrdersFactory == null) { //不存在时，则入库

            /**
             * 入工厂表 jsb_orders_factory
             */
            JsbOrders orderInfo = laundryFactoryVoDao.getOrderInfo(payId);
            JsbOrdersFactory ordersFactory = new JsbOrdersFactory();
            ordersFactory.setOrderId(payId).setUserId(orderInfo.getUserId()).
                    setFactoryId(orderInfo.getShopId())
                    .setFactoryOrdersStatus(1).setType(orderInfo.getShippingType());
            Integer var0 = laundryFactoryVoDao.addOrderFactory(ordersFactory);


            /**
             * 入工厂表 jsb_orders_factory_item
             */
            List<JsbOrdersItem> subOrderList = laundryFactoryVoDao.getSubOrderList(payId);
            List<JsbOrdersFactoryItem> jsbOrdersFactoryItem = subOrderList.stream()
                    .map(jsbOrdersItem -> {
                        JsbOrdersFactoryItem item = new JsbOrdersFactoryItem();
                        item.setOrderFactoryId(var0)
                                .setProductId(jsbOrdersItem.getProductId())
                                .setOrderId(jsbOrdersItem.getOrderId())
                                .setSubOrderId(jsbOrdersItem.getSubOrderId());
                        return item;
                    })
                    .collect(Collectors.toList());

            int var1 = laundryFactoryVoDao.addOrderFactoryItem(jsbOrdersFactoryItem);
        }
    }

    @Transactional
    @ApiOperation(value = "骑手更新商品", notes = "骑手取货", httpMethod = "POST")
    @PostMapping("riderUpdateProduct")
    public WebResponse riderUpdateProduct(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        JSONArray list = jsonObject.getJSONArray("list");
        String orderId = jsonObject.getString("orderId");
        List<ViewOrderDetailsVoRequest> orderListDetailsDtos = JSON.parseArray(JSON.toJSONString(list), ViewOrderDetailsVoRequest.class);
        List<String> imgStr = orderListDetailsDtos.stream().map(ViewOrderDetailsVoRequest::getImgs).collect(Collectors.toList());
        for (String s : imgStr) {
            if (JSBUtil.isEmptyString(s)) {
                return WebResponse.success(ReturnStatusCode.PLEASE_PUT_ON_THE_PICTURE.getCode(), ReturnStatusCode.PLEASE_PUT_ON_THE_PICTURE.getMsg());

            }

        }
        //判断该订单是不是这个骑手的
//        String byOrderInfoByInMy = orderInfoService.findByOrderInfoTc(orderId, userId);
//        if ("1".equals(byOrderInfoByInMy)) {
        Integer subDetails = orderInfoService.updateSubDetails(orderListDetailsDtos);
        if (subDetails > 0) {
            String orderStatus = "2";
            orderInfoService.pickUp(orderStatus, orderId);
            //骑手待结算
            //查询改订单的金额
            int byPaidPrice = orderInfoService.findByPaidPrice(orderId);
            double money = byPaidPrice * Constant.rider_commission_percentage;
            //查询抢单用户id
            String riderInfoId = orderInfoService.findByRiderInfoId(orderId);
            orderSplittingService.riderSplitting(orderId,riderInfoId, (int) money);
            int direction = orderInfoService.findByOrderDirection(orderId);
            String byOrderStatus = orderInfoService.findByOrderStatus(orderId);
            jsbOrderStatusLogService.addLog(orderId, byOrderStatus, String.valueOf(direction));
//                return WebResponse.successData(byOrderInfoByInMy);
        }
//        }
//        return WebResponse.success(ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getCode(), ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getMsg());
        return WebResponse.successData("1");
    }


    @ApiOperation(value = "确认送达", notes = "确认送达", httpMethod = "POST")
    @PostMapping("okUpBack")
    public WebResponse okUpBack(@RequestBody OderPuRequest oderPuRequest) {
//        String byOrderInfoByInMy = orderInfoService.findByOrderInfoTc(oderPuRequest.getOrderId(), oderPuRequest.getUserId());
//        if ("1".equals(byOrderInfoByInMy)) {
        if ("g".equals(oderPuRequest.getDeliveryStatus())) {
            String byUserPhone = orderInfoService.findByUserPhoneBack(oderPuRequest.getOrderId());
            //随机4位验证码
            String phoneCode = JSBUtil.randomGenStrs(4);
            CodeUtil.EndCode(byUserPhone, phoneCode);
            redisUtil.setCacheObject(byUserPhone, phoneCode, 5, TimeUnit.MINUTES);
        } else if ("h".equals(oderPuRequest.getDeliveryStatus())) {
            String byUserPhone = orderInfoService.findByUserPhoneBack(oderPuRequest.getOrderId());
            //随机4位验证码
            String phoneCode = JSBUtil.randomGenStrs(4);
            CodeUtil.EndCode(byUserPhone, phoneCode);
            redisUtil.setCacheObject(byUserPhone, phoneCode, 5, TimeUnit.MINUTES);
        }
        return WebResponse.successData("1");
//        }
//        return WebResponse.success(ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getCode(), ReturnStatusCode.THIS_ORDER_IS_NOT_FOR_CHANGING_RIDERS_PLEASE_CONTACT_CUSTOMER_SERVICE.getMsg());

    }

    @ApiOperation(value = "输入验证码改变状态代签", notes = "输入验证码改变状态代签", httpMethod = "POST")
    @PostMapping("/endCode")
    public WebResponse endCode(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String orderId = jsonObject.getString("orderId");
        String code = jsonObject.getString("code");
        String deliveryStatus = jsonObject.getString("deliveryStatus");
        String userPhone = orderInfoService.findByUserPhoneBack(orderId);

        Object codes = redisUtil.getCacheObject(userPhone);
        if (code.equals(codes)) {
            orderInfoService.updateDeliveryStatus(orderId,deliveryStatus);
            int direction = orderInfoService.findByOrderDirection(orderId);
            String byOrderStatus = orderInfoService.findByOrderStatus(orderId);
            jsbOrderStatusLogService.addLog(orderId, byOrderStatus, String.valueOf(direction));
            //添加到工厂
            HttpUtil.sendPost("http://127.0.0.1:10003/order/mq/riderConfirmedDelivery",null, JSONObject.toJSONString(orderId));
            JSONObject object = new JSONObject();
            object.put("orderId",orderId);
            HttpUtil.sendPost("http://127.0.0.1:10003/order/mq/riderConfirmedDelivery",null, JSONObject.toJSONString(object));
            return WebResponse.successData("1");
        }
        return WebResponse.successData(null);
    }

    //    @ApiOperation(value = "查看已完成的订单", notes = "查看已完成的订单", httpMethod = "POST")
//    @PostMapping("/okOrderInfo")
//    public WebResponse okOrderInfo(@RequestBody String data) {
//        JSONObject jsonObject = JSON.parseObject(data);
//        String orderId = jsonObject.getString("orderId");
//        List<OrderListVo> orderListVos = orderInfoService.okOrderInfo(orderId);
//        for (OrderListVo orderListVo : orderListVos) {
//            //查询改订单的金额
//            int byPaidPrice = orderInfoService.findByPaidPrice(orderListVo.getOrderId());
//            double money = byPaidPrice * 0.05;
//            orderListVo.setMoney(JSBUtil.turnDoubleStr(String.valueOf(money)));
//
//        }
//        return WebResponse.successData(orderListVos);
//    }
    @ApiOperation(value = "骑手拍照放在指定位置", notes = "骑手拍照放在指定位置", httpMethod = "POST")
    @PostMapping("/upImg")
    public WebResponse upImg(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String img = jsonObject.getString("img");
        String orderId = jsonObject.getString("orderId");
        int byOrderDirection = ordersFulfillmentDao.findByOrderDirection(orderId);
        if (byOrderDirection == 2) {
            int upImg = ordersFulfillmentDao.upImg(orderId, img);
            orderInfoService.updateDeliveryStatus(orderId,"i");
            int direction = orderInfoService.findByOrderDirection(orderId);
            String byOrderStatus = orderInfoService.findByOrderStatus(orderId);
            jsbOrderStatusLogService.addLog(orderId, byOrderStatus, String.valueOf(direction));

            //添加到工厂
            String orderStatus = "3";
            orderInfoService.pickUp(orderStatus, orderId);
            JSONObject object = new JSONObject();
            object.put("orderId",orderId);
            HttpUtil.sendPost("http://127.0.0.1:10003/order/mq/riderConfirmedDelivery",null, JSONObject.toJSONString(object));
            return WebResponse.successData("1");
        }
        return WebResponse.successData(null);
    }

    @ApiOperation(value = "发送验证码", notes = "发送验证码", httpMethod = "POST")
    @PostMapping("/endPhoneCode")
    public WebResponse endPhoneCode(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        String orderId = jsonObject.getString("orderId");
        String byUserPhone = orderInfoService.findByUserPhoneBack(orderId);
        //随机4位验证码
        String phoneCode = JSBUtil.randomGenStrs(4);
        CodeUtil.EndCode(byUserPhone, phoneCode);
        redisUtil.setCacheObject(byUserPhone, phoneCode, 5, TimeUnit.MINUTES);
        return WebResponse.successData("1");
    }

    @ApiOperation(value = "查询骑手关注公众号", notes = "查询骑手关注公众号", httpMethod = "POST")
    @PostMapping("findByFollow")
    public WebResponse findByFollow(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        int byFollow = ordersFulfillmentDao.findByFollow(userId);
        return WebResponse.successData(byFollow);
    }

    @ApiOperation(value = "历史订单", notes = "历史订单", httpMethod = "POST")
    @PostMapping("findByHistoricalOrdersDetails")
    public WebResponse findByHistoricalOrdersDetails(@RequestBody HistoricalOrdersDetailsRequest historicalOrdersDetailsRequest) {

        HistoricalOrdersDetailsListVo byHistoricalOrdersDetails = ordersFulfillmentDao.findByHistoricalOrdersDetails(historicalOrdersDetailsRequest.getUserId(), historicalOrdersDetailsRequest.getOrderId());
        List<HistoricalOrdersDetailsListVo.OrderStatusInfo> byOrderStatusLog = ordersFulfillmentDao.findByOrderStatusLog(historicalOrdersDetailsRequest.getUserId(), historicalOrdersDetailsRequest.getOrderId());
        for (HistoricalOrdersDetailsListVo.OrderStatusInfo orderStatusInfo : byOrderStatusLog) {
            if ("1".equals(orderStatusInfo.getOrderDirection())) {
                if ("7".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已接单");
                }
                if ("8".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已取件");

                }
                if ("9".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已送达");

                }
            } else if ("2".equals(orderStatusInfo.getOrderDirection())) {
                if ("7".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已接单");

                }
                if ("8".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已取件");

                }
                if ("9".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已送达");

                }
                if ("a".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已入库（清洗中）");

                }
                if ("b".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已出库（清洗完成）");

                }
                if ("c".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已出库取件");

                }
                if ("d".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已出库送达");

                }
                if ("e".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已完成-订单完毕");

                }
                if ("f".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已交接");

                }
                if ("g".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("已签收");

                }
                if ("h".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("代签收");
                }
                if ("i".equals(orderStatusInfo.getOrderStatus())) {
                    orderStatusInfo.setOrderStatus("放指定位置");

                }
            }

        }
        byHistoricalOrdersDetails.setOrderStatusInfos(byOrderStatusLog);
        return WebResponse.successData(byHistoricalOrdersDetails);
    }

}
